package com.zeus.service;

import com.zeus.mapper.CartInfoMapper;
import com.zeus.mapper.CartMapper;
import com.zeus.mapper.GoodsSkuMapper;
import com.zeus.pojo.Cart;
import com.zeus.pojo.CartInfo;
import com.zeus.pojo.GoodsSku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 冯扬龙
 * @date 2021/4/19 16:33
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartInfoMapper cartInfoMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsSkuMapper goodsSkuMapper;

//挑选好商品以后，点击添加到购物车，要发生的一系列操作
    public int addGoodsToCart(CartInfo cartInfo) {
        int count = cartInfoMapper.selectGoodsToCart(cartInfo);
        //做判断
        if(count > 0){
//            <!--如果商品存在购物车中，则更新购物车中商品的数量-->
              cartInfoMapper.updateCartInfo(cartInfo);
        }else {
//            <!--假如不存在则添加商品到购物车中-->
              cartInfoMapper.addCartInfo(cartInfo);
//              更新购物车总数量（添进来购物车的总类）
            cartMapper.updateCart(cartInfo.getCartId());
        }
//        返回购物车的总数
        return cartMapper.selectCartTotalNum(cartInfo.getCartId());
    }

//首页点击购物车，进入购物车页面，七张联表
    public Cart showCartList(int cartId) {
//根据前端传来的购物车id显示所有的商品属性和信息
//根据购物车id 查询该购物车中的所有sku商品属性信息 sku_properties  2001:3001,2002:3011,2003:3020
        List<GoodsSku> goodsSkuList= goodsSkuMapper.showCartList(cartId);

//将2001:3001,2002:3011,2003:3020 修改为 '2001:3001','2002:3012','2003:3020'
        for (int i = 0; i < goodsSkuList.size(); i++) {
            GoodsSku goodsSku = goodsSkuList.get(i);
            String skuProperties = goodsSku.getSkuProperties();
            skuProperties = skuProperties.replaceAll(",", "','");
            skuProperties = "'" + skuProperties + "'";
            goodsSku.setSkuProperties(skuProperties);
        }
//将cardId和sku商品的属性信息(goodsSkuList)传到mapper查询
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cartId", cartId);
        map.put("list", goodsSkuList);
        Cart cart = cartMapper.selectCartList(map);
        return cart;
    }

//购物车页面，前端点击删除按钮，传回来一个skuid
    public int deleteGoodsFromCart(CartInfo cartInfo) {
      cartInfoMapper.deleteGoodsFromCart(cartInfo);
      cartMapper.updateCart2(cartInfo.getCartId());
      return cartMapper.selectCartTotalNum(cartInfo.getCartId());
    }
}
